package com.hjh.gameforum.service;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.DeleteResponse;
import co.elastic.clients.elasticsearch.core.GetResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 基础Elasticsearch服务
 */
@Service
public abstract class BaseElasticsearchService {

    protected final ElasticsearchClient elasticsearchClient;

    @Autowired
    public BaseElasticsearchService(ElasticsearchClient elasticsearchClient) {
        this.elasticsearchClient = elasticsearchClient;
    }

    protected ElasticsearchClient getClient() {
        return elasticsearchClient;
    }

    /**
     * 索引文档
     */
    public <T> String indexDocument(String indexName, String id, T document) throws IOException {
        IndexResponse response = getClient().index(i -> i
                .index(indexName)
                .id(id)
                .document(document)
        );
        return response.id();
    }

    /**
     * 获取文档
     */
    public <T> T getDocument(String indexName, String id, Class<T> clazz) throws IOException {
        GetResponse<T> response = getClient().get(g -> g
                .index(indexName)
                .id(id), clazz
        );
        return response.source();
    }

    /**
     * 删除文档
     */
    public void deleteDocument(String indexName, String id) throws IOException {
        DeleteResponse response = getClient().delete(d -> d
                .index(indexName)
                .id(id)
        );
    }
}
